/*
 * @description:
 * @Author: lal
 * @Date: 2020-05-25 11:10:44
 * @LastEditors: lal
 * @LastEditTime: 2020-08-26 16:05:12
 */

import { protocol, BrowserWindow } from "electron";
import path from "path";
// import winInstance from "./BrowserWindowInstance";
import log from "electron-log";
const DEV_URL = process.env.WEBPACK_DEV_SERVER_URL;
import {
  createProtocol,
  /* installVueDevtools */
} from "vue-cli-plugin-electron-builder/lib";

const windows = Object.create(null);
protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

/**
 *
 * @param {String} windowId  实例化窗口指定的key,value为实例化的窗口对象
 * @param {Object} opt 窗口配置项
 * @param {String} url  路由路径，#号后面的路径
 */
function createWindow(windowId, opt, url) {
  // 已经创建
  if (windows[windowId]) {
    windows[windowId].setSkipTaskbar(false);
    windows[windowId].focus();

    return false;
  }
  // Create the browser window.
  let defaultOpt = {
    width: 900,
    height: 700,
    // show: false,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__static, "preload.js"),
    },
  };

  opt = Object.assign(defaultOpt, opt);
  let newWindow = new BrowserWindow(opt);
  newWindow.free = false;
  // windows.add(newWindow);
  windows[windowId] = newWindow;

  if (DEV_URL) {
    // Load the url of the dev server if in development mode
    if (url) {
      newWindow.loadURL(`${DEV_URL}#${url}`);
    } else {
      newWindow.loadURL(DEV_URL);
    }
    if (!process.env.IS_TEST) newWindow.webContents.openDevTools();
  } else {
    createProtocol("app");
    // Load the index.html when not in development
    if (url) {
      newWindow.loadURL(`app://./index.html#${url}`);
    } else {
      newWindow.loadURL("app://./index.html");
    }
  }
  // 载入菜单log.info()
  // newWindow.on("focus", () => {
  //   log.info("聚焦focus");
  //   log.info(windowId);
  // });
  // newWindow.once("ready-to-show", () => {
  //   newWindow.show();
  // });
  newWindow.on("close", e => {
    log.info(windowId);
    log.info("开始退出");
    if (windowId == "mainWindow") {
      newWindow.hide();
      newWindow.setSkipTaskbar(true);
      e.preventDefault();
    } else {
      newWindow = null;
      windows[windowId] = null;
      delete windows[windowId];
    }
    // windows.delete(newWindow);
  });
  newWindow.on("closed", () => {
    // log.info(windows);
    log.info("closed");
    newWindow = null;
    delete windows[windowId];
  });

  return newWindow;
}

export { createWindow, windows };
